<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/19
 * Time: 10:11
 */
namespace App\Http\Controllers\Api\V1\Manager\Wx;


use App\Http\Controllers\Controller;
use App\Libs\httpUtil;
use App\Models\WxMenu;
use App\Services\Wx\AliService;
use Illuminate\Http\Request;


class wxCommentController extends Controller
{

  /*  public $appId = "wxd6de23f6859dbdba";
    public $appSecret = "4d96e69326d19b583dfb6d76366768ce";*/

    public function getAccessToken()
    {
        $data = \RedisDB::get('xak-access_token');
        if($data){
            $accessToken = json_decode($data, true);
            return $accessToken['access_token'];
        }else{
            return   $this->refreshAccessToken();
        }
    }

    /**
     * 刷新accessToken
     * @return bool
     */
    private function refreshAccessToken()
    {
        $appId = "wxd6de23f6859dbdba";
        $appSecret = "4d96e69326d19b583dfb6d76366768ce";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
        $http = new httpUtil();
        $data = $http->http_get($url);
        if(!$data){
            return false;
        }

        $result = json_decode($data, true);
        if(!empty($result['errcode'])){
            \Log::error('WxService  refreshAccessToken'.$data);
            return false;
        }
        $result['createTime'] = date("Y-m-d H:i:s",time());

        \RedisDB::setex('xak-access_token',$result['expires_in'],json_encode($result));
        return $result['access_token'];
    }
    public function mediaUpdate(Request $request)
    {
        $file = $request->file('file');
        $filesize = $file->getClientSize();
        if ($filesize == 0) {
            return $this->apiResponse('', config("errorCode.UPLOAD_FILE_BIG"));
        }



        if ($file->isValid()) {
            $realPath = $file->getRealPath();
            $entension = $file->getClientOriginalExtension();
            $clientName = $file->getClientOriginalName();    //客户端文件名称
            $newName = md5(date('ymdhis') . $clientName) . "." . $entension;    //定义上传文件的新名称
            $mimeTye = $file->getMimeType();
            $path = "/service/wxapp/XAK/service/XAK/public/uploads/" . $newName;
            $result = move_uploaded_file($realPath, $path);

            if ($result) {
                $token = $this->getAccessToken();

                $type = "image";  //声明上传的素材类型，这里为image
                //调用接口需要获取token,这里使用一个封装好的调取access_token的函数
                $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;
                //这里是请求地址，token和素材类型通过get方式传递
                $file_path = $path;
                //这里声明文件的路径，使用绝对路径
                $file_data = array('media'  => '@'.$file_path);
                //传递的数组，方式一：使用'@'符号加上文件的绝对路径来指引文件。这种方式适合PHP5.5之前的版本，
                $file_data = array("media"  => new \CURLFile($file_path));
                //传递的数组，方式二：从PHP5.5版本以后，引入了新的CURLFile 类来指向文件，参数传入的也是绝对路径
                $ch = curl_init();
                //初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。
                curl_setopt($ch , CURLOPT_URL , $url);
                //需要获取的URL地址，也可以在curl_init()函数中设置。
                curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
                //使用PHP curl获取页面内容或提交数据，有时候希望返回的内容作为变量储存，
                //而不是直接输出。这个时候就必需设置curl的CURLOPT_RETURNTRANSFER选项为1或true
                curl_setopt($ch , CURLOPT_POST, 1);
                //发送一个POST请求
                curl_setopt($ch , CURLOPT_POSTFIELDS, $file_data);
                //传递一个关联数组，生成multipart/form-data的POST请求
                $output = curl_exec($ch);//发送请求获取结果
                curl_close($ch);//关闭会话

                $output = json_decode($output);
                $output->path = 'http://118.89.20.224:9003/uploads/' . $newName;
                /*$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" . $access_token . "&type=image";
                $httpUrl = new httpUtil();
                $res = $httpUrl->http_post($url, $filedata);*/
                return $this->apiResponse($output);
            }
            return $this->apiResponse('', '上传文件失败', 10000);



        }

    }

}
